/**
 * 待我阅读
 */
import React, { Fragment, useEffect, useCallback, useState } from 'react';
import { connect } from 'umi';
import { Form, Table, Card } from 'antd';
import { utils } from 'vv-frontend-components';
import { history } from 'umi';
import xss from 'xss';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import ApplyStatus from '@/components/ApplyStatus';
import { withRoutePage } from '@/utils/enhanceUtils';
import PageRouter from '@/components/PageRouter/PageRouter';
import Pagination from '@/components/Pagination';
import TableFilter from '@/components/TableFilter';
import styles from './index.less';
import SearchList from '../WaitApproval/SearchList';

const List = ({ myreading, dispatch, loading, applyCommon }) => {
    const { myreadingPagination: pagination, myreadingList: data } = myreading;
    const [advancedSearch, setAdvancedSearch] = useState({});
    const { statusPropsList } = applyCommon;
    const [sorters, setSorters] = useState(''); // 排序储存
    const newState = (record, showtype) => {
        const oldStatus = `${record.status}`;
        const newcandidateUsers = record.candidateUsers.split('#');
        let status = '';
        let newUsers = '';
        let statusString = '';
        if (newcandidateUsers.length > 1) {
            newUsers = `${newcandidateUsers.length}人-`;
        } else {
            newUsers = `${record.candidateUsers}-`;
        }
        statusPropsList.forEach(item => {
            if (item.key === oldStatus) {
                status = item.value;
            }
        });
        if (showtype) {
            if (record.candidateUsers === '') {
                statusString = `${status}`;
            } else {
                statusString = `${newUsers}${status}`;
            }
            return statusString;
        }
        return (
            <div>
                <ApplyStatus status={record.status} />
                {record.candidateUsers === '' ? null : newUsers}
                {status}
            </div>
        );
    };
    const columns = [
        {
            title: '申请主题',
            dataIndex: 'applicationName',
            key: 'applicationName',
            width: '20%',
            render: (text, record) => (
                <span
                    onClick={e => {
                        e.preventDefault();
                        const {
                            applicationNo,
                            formDeploymentId
                            // id
                        } = record;
                        history.push({
                            pathname: '/personal/portal/flow/mine/approvalDetail',
                            query: {
                                applicationNo,
                                formDeploymentId
                            }
                        });
                    }}
                >
                    {record.readStatus === 0 ? (
                        <i className="iconfont icontable_icon_unread_default-"></i>
                    ) : (
                        <i className="iconfont icontable_icon_alreadyread_default"></i>
                    )}
                    {record.readStatus === 0 ? (
                        <a style={{ marginLeft: '5px' }}>{text}</a>
                    ) : (
                        <span className={styles.readstatus}>{text}</span>
                    )}
                </span>
            )
        },
        {
            title: '申请单摘要',
            dataIndex: 'applicationNote',
            key: 'applicationNote',
            render(text) {
                return (
                    <div
                        style={{
                            display: '-webkit-box',
                            WebkitLineClamp: 5,
                            overflow: 'hidden',
                            maxHeight: 105,
                            WebkitBoxOrient: 'vertical'
                        }}
                    >
                        <span style={{ wordBreak: 'break-all' }} dangerouslySetInnerHTML={{ __html: xss(text) }} />
                    </div>
                );
            }
        },
        {
            title: '发起时间',
            dataIndex: 'startingTime',
            key: 'startingTime',
            width: 200,
            sorter: () => {},
            render: text => <div>{text === '' ? '——' : text}</div>
        },
        {
            title: '完成时间',
            dataIndex: 'endTime',
            key: 'endTime',
            width: 200,
            sorter: () => {},
            render: text => <div>{text === '' ? '——' : text}</div>
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'states',
            width: 150,
            filters: [
                { key: 2, value: '1', text: '待发送' },
                { key: 3, value: '2', text: '审批中' },
                { key: 4, value: '6', text: '已退回' },
                { key: 5, value: '5', text: '已撤销' },
                { key: 6, value: '4', text: '已通过' },
                { key: 7, value: '3', text: '未通过' }
            ],
            filterDropdown: filterProps => <TableFilter {...filterProps} />,
            filterMultiple: false,
            render: (text, record) => newState(record)
        }
    ];
    const fetchMyreadingList = Fields => {
        dispatch({
            type: 'myreading/fetchMyreadingList',
            payload: utils.deepTrim({
                ...Fields,
                pageNo: pagination.current,
                pageSize: pagination.pageSize,
                orderBy: myreading.order,
                status: myreading.status
            })
        });
    };

    const onSearch = useCallback(Fields => {
        setAdvancedSearch(Fields);
        if (myreading.myreadingPagination.current !== 1) {
            dispatch({
                type: 'myreading/save',
                payload: {
                    myreadingPagination: {
                        ...myreading.myreadingPagination,
                        current: 1
                    }
                }
            });
        } else {
            fetchMyreadingList(Fields);
        }
    });

    const handlePaginationChange = nextPagination => {
        dispatch({
            type: 'myreading/save',
            payload: {
                myreadingPagination: {
                    ...myreading.myreadingPagination,
                    ...nextPagination
                }
            }
        });
    };

    // 发起排序
    const handleTableChange = (_, filters = {}, sorter) => {
        let sorterField;
        let orderBy;
        let status = '';

        if (Array.isArray(filters.states)) {
            const [firstState = ''] = filters.states;
            status = firstState;
        }

        if (sorter && sorter.field && sorter.order) {
            if (sorter.field === 'startingTime') {
                sorterField = 't1.starting_time';
            }
            if (sorter.field === 'endTime') {
                sorterField = 'endnull desc,t1.end_time';
            }
            const order = sorter.order.trim().split('end')[0];
            orderBy = `${sorterField} ${order}`;
        } else if (typeof sorters === 'string') {
            dispatch({
                type: 'myreading/save',
                payload: {
                    order: ''
                }
            });
        }
        dispatch({
            type: 'myreading/save',
            payload: {
                order: orderBy || '',
                status
            }
        });
        if (sorter && sorters !== sorter) {
            setSorters(sorter);
            dispatch({
                type: 'myreading/save',
                payload: {
                    order: orderBy || '',
                    myreadingPagination: {
                        ...myreading.myreadingPagination,
                        current: 1
                    }
                }
            });
        }
    };
    // 每当分页数或页数改变时均应该重新请求表格数据
    useEffect(() => {
        fetchMyreadingList(advancedSearch);
    }, [myreading.order, myreading.status, pagination.pageSize, pagination.current]);
    useEffect(
        () => () => {
            dispatch({
                type: 'myreading/save',
                payload: {
                    order: '',
                    myreadingPagination: {
                        current: 1,
                        pageSize: 10
                    }
                }
            });
        },
        []
    );
    return (
        <PageHeaderWrapper>
            <PageRouter type="myflow">
                <Fragment>
                    <Card bordered={false} className={styles.tableread}>
                        <SearchList onSearch={onSearch} />
                        <Table
                            bordered={false}
                            columns={columns}
                            loading={loading}
                            dataSource={data}
                            onChange={handleTableChange}
                            pagination={false}
                        />
                        <Pagination {...pagination} onChange={handlePaginationChange} />
                    </Card>
                </Fragment>
            </PageRouter>
        </PageHeaderWrapper>
    );
};
export default withRoutePage(
    connect(({ loading, myreading, applyCommon }) => ({
        myreading,
        applyCommon,
        loading: loading.models.myreading
    }))(Form.create()(List))
);
